package com.itshizhan.itjidancideveloper.controller.webfront;

import com.itshizhan.itjidancideveloper.dao.ArticleCategoryDao;
import com.itshizhan.itjidancideveloper.dao.ArticleDao;
import com.itshizhan.itjidancideveloper.models.Article;
import com.itshizhan.itjidancideveloper.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;

@RestController()
@RequestMapping("/webfront/article")
public class ArticleFrontController {
	@Autowired
	ArticleDao articleDao;
	@Autowired
	ArticleCategoryDao articleCategoryDao;
	@PostMapping("/list")
	public Response<Page<Article>> getList(@RequestParam("pageIndex") Integer pageIndex,
																				 @RequestParam("pageSize") Integer pageSize,
																				 @RequestParam("categoryId") String categoryId
	) {
		//注意：从第0页开始的
		PageRequest pageable = PageRequest.of(pageIndex - 1, pageSize);
		Specification<Article> spec  = (Specification<Article>) (root, query, cBuilder) -> {
			if(categoryId.equals("0")){
				// 前台只展示已审核的文章
				Predicate stateCondition = cBuilder.equal(root.get("state"), 1);
				query.where(stateCondition);
			}else{
				Predicate categoryCondition = cBuilder.equal(root.get("articleCategory").get("id"), categoryId);
				// 前台只展示已审核的文章
				Predicate stateCondition = cBuilder.equal(root.get("state"), 1);
				query.where(categoryCondition,stateCondition);
			}
			return null;
		};
		Page<Article> pageArticle = articleDao.findAll(spec,pageable);
		// 也可以通过原生Sql进行查询，如下：
		// Page<Article> pageArticle = articleDao.findByCategoryId(categoryId, pageable);
		return Response.success(pageArticle);
	}

	@PostMapping("/list/{userId}")
	public Response<Page<Article>> getListByUser(@RequestParam("pageIndex") Integer pageIndex,
										   @RequestParam("pageSize") Integer pageSize, @PathVariable("userId") String userId
	) {
		//注意：从第0页开始的
		PageRequest pageable = PageRequest.of(pageIndex - 1, pageSize);
		Specification<Article> spec  = (Specification<Article>) (root, query, cBuilder) -> {

			Predicate categoryCondition = cBuilder.equal(root.get("userId"), Long.valueOf(userId));
			// 前台只展示已审核的文章
			Predicate stateCondition = cBuilder.equal(root.get("state"), 1);
			query.where(categoryCondition,stateCondition);
			return null;
		};
		Page<Article> pageArticle = articleDao.findAll(spec,pageable);
		// 也可以通过原生Sql进行查询，如下：
		// Page<Article> pageArticle = articleDao.findByCategoryId(categoryId, pageable);
		return Response.success(pageArticle);
	}

	@GetMapping("/detail/{id}")
	public Response<Article> getArticleDetail(@PathVariable("id") String articleId) {
		System.out.println(articleId);
		Article article = articleDao.findById(Integer.valueOf(articleId)).orElse(null);
		return  Response.success(article);
	}
}
